package com.eyeem.recyclerviewtools.sample;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.eyeem.recyclerviewtools.LoadMoreOnScrollListener;
import com.eyeem.recyclerviewtools.sample.adapter.AnimalsAdapter;
import com.eyeem.recyclerviewtools.sample.adapter.StickyWrapAdapter;
import com.eyeem.recyclerviewtools.sample.utils.BlurUtil;
import com.eyeem.recyclerviewtools.sample.utils.RecyclerItemClickListener;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersTouchListener;

import java.security.SecureRandom;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by budius on 26.05.16.
 */
public class MaterialDesiginStickyActivity3 extends BaseActivity implements LoadMoreOnScrollListener.Listener {
    private LinearLayout head_layout;
    private SwipeRefreshLayout swipeRefreshLayout;
    //private TabLayout toolbar_tab;
    private RecyclerView recycler;
    private ImageView image;
    private CollapsingToolbarLayout mCollapsingToolbarLayout;
    //private DataAdapter adapter;
    private AnimalsHeadersAdapter adapter;
    private StickyWrapAdapter wrapAdapter;
    //添加的头部个数
    private int HEADERCOUNT = 0;

    SampleActivity.CollapsingToolbarLayoutState state = SampleActivity.CollapsingToolbarLayoutState.EXPANDED;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_material_design3);
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

        image = (ImageView) findViewById(R.id.image);
        AppBarLayout app_bar_layout = (AppBarLayout) findViewById(R.id.app_bar_layout);
        final Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        head_layout = (LinearLayout) findViewById(R.id.head_layout);
        //
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        mCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout);

        setBackgroundImage();

        mToolbar.setTitle("涩郎");
        mCollapsingToolbarLayout.setTitle("");
        //使用CollapsingToolbarLayout必须把title设置到CollapsingToolbarLayout上，设置到Toolbar上则不会显示
        app_bar_layout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                swipeRefreshLayout.setEnabled(verticalOffset >= 0);
                if (verticalOffset == 0) {
                    if (state != SampleActivity.CollapsingToolbarLayoutState.EXPANDED) {
                        state = SampleActivity.CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                        mCollapsingToolbarLayout.setTitle("");//设置title为EXPANDED
                        mToolbar.setTitle("涩郎");
                    }
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    if (state != SampleActivity.CollapsingToolbarLayoutState.COLLAPSED) {
                        mCollapsingToolbarLayout.setTitle("");//设置title不显示
                        state = SampleActivity.CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                        mToolbar.setTitle("涩郎");
                    }
                } else {
                    if (state != SampleActivity.CollapsingToolbarLayoutState.INTERNEDIATE) {
                        mCollapsingToolbarLayout.setTitle("");//设置title为INTERNEDIATE
                        state = SampleActivity.CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                        mToolbar.setTitle("涩郎");
                    }
                }
            }
        });
        Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                String msg = "";
                switch (menuItem.getItemId()) {
                    case R.id.action_settings:
                        msg += "设置";
                        break;
                }

                if (!msg.equals("")) {
                    Toast.makeText(MaterialDesiginStickyActivity3.this, msg, Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        };

        mToolbar.setOnMenuItemClickListener(onMenuItemClick);
        //toolbar_tab = (TabLayout) findViewById(toolbar_tab);
        recycler = (RecyclerView) findViewById(R.id.recycler);

        mCollapsingToolbarLayout.setExpandedTitleGravity(Gravity.CENTER);
        mCollapsingToolbarLayout.setCollapsedTitleGravity(Gravity.CENTER);


        //------------sticky------------
        // Adapter
        //adapter = DataAdapter.generateRandom(this);
        adapter = new AnimalsHeadersAdapter();
        adapter.add("Animals below!");
        adapter.addAll(getDummyDataSet());
        wrapAdapter = new StickyWrapAdapter(adapter);
        // Add the sticky headers decoration
        final StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(adapter);
        recycler.addItemDecoration(headersDecor);
        // Add touch listeners
        StickyRecyclerHeadersTouchListener touchListener =
                new StickyRecyclerHeadersTouchListener(recycler, headersDecor);
        touchListener.setOnHeaderClickListener(
                new StickyRecyclerHeadersTouchListener.OnHeaderClickListener() {
                    @Override
                    public void onHeaderClick(View header, int position, long headerId) {
                        Toast.makeText(MaterialDesiginStickyActivity3.this, "Header position: " + position + ", id: " + headerId,
                                Toast.LENGTH_SHORT).show();
                    }
                });
        recycler.addOnItemTouchListener(touchListener);
        recycler.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                adapter.remove(adapter.getItem(position - HEADERCOUNT));
            }
        }));
        adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                headersDecor.invalidateHeaders();
            }
        });
        //------------sticky------------


        // Layout manager
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recycler.setLayoutManager(layoutManager);
        recycler.setAdapter(wrapAdapter);
        // Header
        //添加的头部个数
//        wrapAdapter.addHeader(new Header(this));
//        HEADERCOUNT++;
//        wrapAdapter.addHeader(new Header(this));
//        HEADERCOUNT++;
        // Load more scroller
        recycler.addOnScrollListener(new LoadMoreOnScrollListener(this));
        //
        dismissRefresh(swipeRefreshLayout);
    }

    private String[] getDummyDataSet() {
        return getResources().getStringArray(R.array.animals);
    }

    private void setBackgroundImage() {
        Observable.create(
                new Observable.OnSubscribe<BitmapDrawable>() {
                    @Override
                    public void call(Subscriber<? super BitmapDrawable> subscriber) {
                        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.bg);
                        BitmapDrawable bitmapDrawable = new BitmapDrawable(BlurUtil.fastblur(MaterialDesiginStickyActivity3.this, bitmap, 180));
                        subscriber.onNext(bitmapDrawable);
                        subscriber.onCompleted();
                    }
                })
                .subscribeOn(Schedulers.newThread())// 在非UI线程中执行
                .observeOn(AndroidSchedulers.mainThread())// 在UI线程中执行结果
                .subscribe(new Subscriber<BitmapDrawable>() {
                    @Override
                    public void onNext(BitmapDrawable bitmapDrawable) {
                        //head_layout.setBackgroundDrawable(bitmapDrawable);
                        //mCollapsingToolbarLayout.setContentScrim(bitmapDrawable);
                        image.setBackground(bitmapDrawable);
                    }

                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_space, menu);
        return true;
    }


    @Override
    public void onLoadMore(RecyclerView recyclerView) {
        //toast("Load more");
        wrapAdapter.showLoadMore();
        recyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
//                for (int i = 0; i < 5; i++) {
//                    adapter.data.add(Data.newRandom(MaterialDesiginActivity3.this));
//                }
//
//                if (recycler.getLayoutManager() instanceof StaggeredGridLayoutManager) {
//                    StaggeredLayoutManagerUtils.onItemChanged(recycler, 0);
//                }
//                adapter.notifyDataSetChanged();
                wrapAdapter.hideLoadMore();

            }
        }, 1000);
    }


    private class AnimalsHeadersAdapter extends AnimalsAdapter<RecyclerView.ViewHolder>
            implements StickyRecyclerHeadersAdapter<RecyclerView.ViewHolder> {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.view_item, parent, false);
            return new RecyclerView.ViewHolder(view) {
            };
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            TextView textView = (TextView) holder.itemView;
            textView.setText(getItem(position));
        }

        @Override
        public long getHeaderId(int position) {
            //TODO 当HEADERCOUNT>0时有bug:当某组的数据小于等于HEADERCOUNT 条时，Header显示错误
            if (HEADERCOUNT == 0) {
                return getItem(position).charAt(0);
            } else {
                if (position < HEADERCOUNT) {
                    return -1;
                } else {
                    return getItem(position - HEADERCOUNT).charAt(0);
                }
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.view_header, parent, false);
            return new RecyclerView.ViewHolder(view) {
            };
        }

        @Override
        public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int position) {
            TextView textView = (TextView) holder.itemView;
            textView.setText(String.valueOf(getItem(position).charAt(0)));
            holder.itemView.setBackgroundColor(getRandomColor());
        }

        private int getRandomColor() {
            SecureRandom rgen = new SecureRandom();
            return Color.HSVToColor(150, new float[]{
                    rgen.nextInt(359), 1, 1
            });
        }

    }
}
